package com.zrrd.jt_admin.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zrrd.jt_admin.common.bo.UserLevelBo;
import com.zrrd.jt_admin.common.entity.User;
import com.zrrd.jt_admin.common.entity.UserLevel;
import com.zrrd.jt_admin.common.page.UserPageVo;
import com.zrrd.jt_admin.common.vo.UserVo;
import com.zrrd.jt_admin.user.mapper.UserMapper;
import com.zrrd.jt_admin.user.service.UserLevelService;
import com.zrrd.jt_admin.user.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wanjl
 * @since 2024-06-30
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserLevelService userLevelService;


    /**
     * 分页查询|多条件搜索
     *
     * @param page
     * @param limit
     * @param keyword
     * @param userLevelId
     * @return
     */
    @Override
    public UserPageVo finByPage(int page, Integer limit, String keyword, Integer userLevelId) {
        PageHelper.startPage(page, limit);
        List<User> list = lambdaQuery().like(keyword != null && keyword != "", User::getUsername, keyword)
                .eq(userLevelId != null, User::getUserLevelId, userLevelId)
                .list();
        PageInfo<User> pageInfo = new PageInfo<>(list);
        UserPageVo userPageVo = new UserPageVo();

        List<UserVo> userVoList = pageInfo.getList().stream().map(user -> {
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user, userVo);
            UserLevel userLevel = userLevelService.getById(user.getUserLevelId());
            userVo.setUserLevel(userLevel);
            return userVo;
        }).collect(Collectors.toList());
        userPageVo.setList(userVoList);
        userPageVo.setTotalCount(pageInfo.getTotal());

        List<UserLevelBo> userLevelBoList = userLevelService.list().stream().map(userLevel -> {
            UserLevelBo userLevelBo = new UserLevelBo();
            userLevelBo.setId(userLevel.getId());
            userLevelBo.setName(userLevel.getName());
            return userLevelBo;
        }).collect(Collectors.toList());

        userPageVo.setUserLevel(userLevelBoList);

        return userPageVo;
    }
}
